import React, {useEffect, useRef, useState} from 'react';

// @ts-ignore
import {CapsuleChart} from '@jiaminghi/data-view-react';
import PageContainer from "@ant-design/pro-layout/es/components/PageContainer";
import "./index.css";
import {Card, Form, message, Spin} from "antd";
import {ProFormDateRangePicker, ProFormText, QueryFilter} from "@ant-design/pro-form";
import ProTable, {ActionType} from '@ant-design/pro-table';
import {useRequest} from "@@/plugin-request/request";
import {hooksSet, modifyJsonArray} from "@/assets/utils/utils";
// @ts-ignore
import $ from 'jquery';
import {getDateString} from "@/assets/utils/dateUtils";
import moment from "moment";
import {PageParamAnalysis} from "@/pages/analysis/PageParamAnalysis/data";
import {
  list,
  // listChildCity,
  listChildren,
  listCity,
  // listVisitBefore,
  // listVisitBeforeCity
} from "@/pages/analysis/PageParamAnalysis/service";
import {getOption, initECharts, makeData} from "@/assets/utils/eChartsUtils";

const PageAnalysisTools: React.FC<{}> = () => {

  const [spinning, setSpinning] = useState(false)
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  form.setFieldsValue(Object.assign({}, {
    // url: "https://wap.jx.10086.cn/hui/login/otherLogin",
    // dateRange: [getDateString("yyyyMMdd"), getDateString("yyyyMMdd")],
    url: "https://wap.jx.10086.cn",
    dateRange: ['20210425', '20210426'],
    current: 1,
    size: 10
  }, form.getFieldsValue()))

  const [listData, setListData] = useState([]);
  // const [visitBeforeStatistic, setVisitBeforeStatistic] = useState([]);

  /**
   * 获取列表
   */
  const listRun = useRequest((params?: any, loading?: any) => list(params), {
    manual: true,
    onSuccess: (result, params) => {
      hooksSet(setListData, result, () => {
        listCityRun(Object.assign({}, form.getFieldsValue(), {
          url: result[0]?.url,
          key: result[0]?.key
        }))
        // 刷新
        actionRef?.current?.reload()
        // 关闭加载中的弹框
        params[1] && params[1]()
        // 关闭spanning
        setSpinning(false)
        $('<style>.ant-table-row-level-0:first-child{background-color: rgb(197,227,253);}</style>').appendTo('head');
      })
    }
  }).run

  /**
   * 获取地市
   */
  const listCityRun = useRequest((params?: PageParamAnalysis, loading?: any) => listCity(params), {
    manual: true,
    onSuccess: (result, params) => {
      console.log(result)
      // 生成柱状图
      initECharts("cityBarECharts", getOption({
        type: "bar",
        smooth: true,
        dataArray: [
          {legend: "PV", data: makeData(result, "cityName", "pv")},
          {legend: "UV", data: makeData(result, "cityName", "uv")}
        ]
      }))
      // 关闭加载中的弹框
      params[1] && params[1]()
      // 关闭spanning
      setSpinning(false)
    }
  }).run

  /**
   * 获取子节点
   */
  const listChildrenRun = useRequest((params?: any, loading?: any) => listChildren(params), {
    manual: true,
    onSuccess: (result, params) => {
      hooksSet(setListData, modifyJsonArray(listData, "key", params[0].key, {children: result}), () => {
        actionRef?.current?.reload()
        // 关闭加载中的弹框
        params[1] && params[1]()
        // 关闭spanning
        setSpinning(false)
      })
    }
  }).run

  // /**
  //  * 获取子节点地市
  //  */
  // const listChildCityRun = useRequest((params?: PageParamAnalysis, loading?: any) => listChildCity(params), {
  //   manual: true,
  //   onSuccess: (result, params) => {
  //     let data: any[] = [];
  //     result.forEach((n: PageParamAnalysis) => {
  //       data.push({name: n.cityName, value: n.uv})
  //     })
  //     // 关闭加载中的弹框
  //     params[1] && params[1]()
  //     // 关闭spanning
  //     setSpinning(false)
  //   }
  // }).run

  // /**
  //  * 获取访前
  //  */
  // const listVisitBeforeRun = useRequest((params?: any, loading?: any) => listVisitBefore(params), {
  //   manual: true,
  //   onSuccess: (result, params) => {
  //     hooksSet(setVisitBeforeStatistic, modifyJsonArray(visitBeforeStatistic, "key", params[0].key, {children: result}), () => {
  //       actionRef?.current?.reload()
  //       // 关闭加载中的弹框
  //       params[1] && params[1]()
  //       // 关闭spanning
  //       setSpinning(false)
  //     })
  //   }
  // }).run
  //
  // /**
  //  * 获取访前地市
  //  */
  // const listVisitBeforeCityRun = useRequest((params?: PageParamAnalysis, loading?: any) => listVisitBeforeCity(params), {
  //   manual: true,
  //   onSuccess: (result, params) => {
  //     let data: any[] = [];
  //     result.forEach((n: PageParamAnalysis) => {
  //       data.push({name: n.cityName, value: n.uv})
  //     })
  //     // 关闭加载中的弹框
  //     params[1] && params[1]()
  //     // 关闭spanning
  //     setSpinning(false)
  //   }
  // }).run

  useEffect(() => {
    setSpinning(true)
    listRun(form.getFieldsValue(), message.loading('正在加载'))
  }, [])

  return (
    <PageContainer>
      <Card>
        <QueryFilter
          defaultColsNumber={100}
          form={form}
          onFinish={async (values: any) => {
            form.setFieldsValue(values)
            setSpinning(true)
            listRun(form.getFieldsValue(), message.loading('正在加载'))
          }}
        >
          <ProFormText name="url" label="url" rules={[{required: true}]} colSize={9 / 6}/>
          <ProFormDateRangePicker name="dateRange" label="时间区间" rules={[{required: true}]} fieldProps={{
            format: "YYYYMMDD",
            disabledDate: (currentDate) => currentDate && currentDate > moment(getDateString("yyyyMMdd"), 'YYYYMMDD')
          }}/>
          <Form.Item key={"current"} name={"current"} hidden={true}/>
          <Form.Item key={"size"} name={"size"} hidden={true}/>
        </QueryFilter>
      </Card>
      <Spin spinning={spinning}>
        <div style={{paddingTop: '24px'}}>
          <Card title={"页面参数分析数据"}>
            <ProTable
              columns={[
                {
                  dataIndex: 'title',
                  title: '标题',
                  width: 200,
                },
                {
                  dataIndex: 'url',
                  title: 'url',
                  ellipsis: true,
                },
                {
                  dataIndex: 'pv',
                  title: 'pv',
                  width: 100
                },
                {
                  dataIndex: 'uv',
                  title: 'uv',
                  width: 100
                }
              ]}
              actionRef={actionRef}
              pagination={false}
              search={false}
              toolBarRender={false}
              request={() => {
                return Promise.resolve({
                  data: listData,
                  success: true
                })
              }}
              expandable={{
                onExpand: (expanded, record: any) => {
                  // 展开时，查询子节点
                  if (expanded) {
                    setSpinning(true)
                    listChildrenRun(Object.assign({}, form.getFieldsValue(), {
                      url: record.url,
                      key: record.key
                    }), message.loading('正在加载'))
                  }
                }
              }}
              onRow={(record: any, index) => {
                return {
                  // 获取地市信息
                  onClick: (event) => {
                    // 删除默认设置的高亮，伪类
                    $('<style>.ant-table-row-level-0:first-child{background-color: white;}</style>').appendTo('head');
                    // @ts-ignore以前设置的长亮取消
                    $(".ant-table-row").each((i, n) => {
                      $(n).css("background-color", "")
                    })
                    // @ts-ignore设置背景长亮
                    $("[data-row-key='" + record.key + "']").css("background-color", "rgb(197,227,253)")
                    // 获取地市信息
                    setSpinning(true)
                    listCityRun(Object.assign({}, form.getFieldsValue(), {
                      url: record.url,
                      key: record.key
                    }), message.loading('正在加载'))
                  }
                }
              }}
            />
          </Card>
        </div>
        <div style={{paddingTop: '24px'}}>
          <Card title={"地市维度拆分"}>
            <div style={{width: "100%", height: "400px"}} id={"cityBarECharts"}></div>
          </Card>
        </div>
        <div style={{paddingTop: '24px'}}>
          <Card title={"地市维度拆分"}>
          </Card>
        </div>
      </Spin>
    </PageContainer>
  );
};

export default PageAnalysisTools;
